// components/progressbar/progressbar.js
let movableAreaWidth = 0; // 滑动区域宽
let movableViewWidth = 0; // 滑块宽
const backgroundAudioManager = wx.getBackgroundAudioManager();
let currentSec = -1; // 当前时间 ---> 批对时间经常刷新
let isTouch = false; //拖拽时不在自动获取时间
let duration = ''; // 总时长
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isSame:{
      type:Boolean,
      value:false   
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    showTime: {
      currentTime: '00:00',
      totalTime: '00:00'
    },
    movavleDis: 0,
    progress: 0
  },
  /**
   * 声明周期
   */
  lifetimes: {
    /**
     * 当页面加载完成
     */
    ready() {
      if(this.properties.isSame && this.data.showTime.currentTime == '00:00'){
        this._setTime()
      }


      //获取移动区域宽度
      this._getMovableDis();
      //bgm事件绑定
      this._bingBGMEvent();
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    //滑动事件
    onChange(event) {
      if (event.detail.source === 'touch') {
        isTouch = true;
        this.data.progress = event.detail.x / (movableAreaWidth - movableViewWidth) * 100;
        this.data.movavleDis = event.detail.x
      }
    },
    //松开事件
    onTouchEnd() {
      const currentTimeFmt = this._formatTime(Math.floor(backgroundAudioManager.currentTime));
      this.setData({
        progress: this.data.progress,
        movavleDis: this.data.movavleDis,
        ['showTime.currentTime']: `${currentTimeFmt.min}:${currentTimeFmt.sec}`
      })
      backgroundAudioManager.seek(Math.floor(duration * this.data.progress / 100))
      isTouch = false;
    },
    //获取当前滑动区域/滑块宽度
    _getMovableDis() {
      const query = this.createSelectorQuery();
      query.select(".movable-area").boundingClientRect();
      query.select(".movable-view").boundingClientRect();
      query.exec((rect) => {
        movableAreaWidth = rect[0].width;
        movableViewWidth = rect[1].width;
        // console.log(rect)
      })
    },
    //绑定bgm事件
    _bingBGMEvent() {
      // 可以播放
      backgroundAudioManager.onCanplay(() => {
        if (typeof backgroundAudioManager.duration != 'undefined') {
          this._setTime();
        } else {
          setTimeout(() => {
            this._setTime();
          }, 2000)
        }
      })
      //播放的时候
      backgroundAudioManager.onPlay(() => {
        isTouch = false
        this.triggerEvent("musicPlay")
      })
      //等待
      backgroundAudioManager.onWaiting(() => {

      })
      //出错
      backgroundAudioManager.onError(() => {

      })
      //暂停
      backgroundAudioManager.onPause(() => {
        /**
         * 父级控制
         */
        this.triggerEvent("musicPause")
      })
      //时间更新
      backgroundAudioManager.onTimeUpdate(() => {
        if (!isTouch) {
          const currentTime = backgroundAudioManager.currentTime;
          const duration = backgroundAudioManager.duration;
          const currentTimeFmt = this._formatTime(currentTime);
          const sec = currentTime.toString().split('.')[0]
          if (sec != currentSec) {
            this.setData({
              movavleDis: (movableAreaWidth - movableViewWidth) * (currentTime / duration),
              progress: currentTime / duration * 100,
              ['showTime.currentTime']: `${currentTimeFmt.min}:${currentTimeFmt.sec}`
            })
            currentSec = sec
            //联动歌词
            this.triggerEvent('updataTime',{
              currentTime
            })
          }
        }

      })
      //播放完成
      backgroundAudioManager.onEnded(() => {
        /**
         * 组件通讯，子传父
         */
        this.triggerEvent('musicEnd');
      })
    },
    //设置时间
    _setTime() {
      duration = backgroundAudioManager.duration;
      const durationFmt = this._formatTime(duration)
      this.setData({
        ['showTime.totalTime']: `${durationFmt.min}:${durationFmt.sec}`
      })
    },
    //格式化时间
    _formatTime(duration) {
      const min = Math.floor(duration / 60);
      const sec = Math.floor(duration % 60);
      return {
        "min": this._parse0(min),
        "sec": this._parse0(sec)
      }
    },
    //补0
    _parse0(sec) {
      return sec < 10 ? '0' + sec : sec;
    }
  }
})